import { expect } from '@jest/globals';
import * as execa from 'execa';
import fs from 'fs-extra';
import fsExtra from 'fs-extra';
import JSON5 from 'json5';
import path from 'path';

import { initExecuteCommand, runHvigorAsync } from '../../common/common';
import { commonConfig } from '../../plugins/common-config';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  IsEnable,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
  SignType
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOption } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API10,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility
  },
  modulesOption: {
    [ModuleTemplateType.SharedLibrary]: 1,
  }
};
const taskConfig: TestTaskOption = {
  caseLevel: CaseLevel.L1,
  sign: SignType.NoSign,
  ohpmInstall: IsEnable.DisAble,
};

const testFun: TestCaseFun = async (project, taskConfig, record) => {
  // 读取的 路径 path.resolve(project.getModule('entry').moduleRootPath(),'oh-package.json5');
  const data = await fs.readFile(path.resolve(project.getModule('entry').moduleRootPath(),
    'oh-package.json5'));

  // 解析JSON5文件
  const obj = JSON5.parse(data.toString());

  // 修改对象
  obj.dynamicDependencies = { 'shareLibrary': 'file:../shareLibrary' };

  // 写回文件
  await fsExtra.writeFile(path.resolve(project.getModule('entry').moduleRootPath(),
    'oh-package.json5'), JSON5.stringify(obj, null, 2));

  // 执行ohpm install
  await execa.command(commonConfig.ohpmInstallCommand, {
    cwd: path.resolve(project.getModule('entry').moduleRootPath())
  });
  const projectRoot = project.projectRootPath();
  const commands = initExecuteCommand({
    mode: 'module',
    product: 'default',
    tasks: 'assembleHap',
  });
  const result = await runHvigorAsync(projectRoot, commands);
  record.addStep('执行hap编译构建', result);
  expect(result.stdout).toContain('BUILD SUCCESSFUL');
  const dataModule = await fs.readFile(
    path.resolve(project.getModule('entry').moduleRootPath(),
      'build/default/intermediates/res/default/module.json')
  );

  // 解析JSON5文件
  const dataModuleJson = JSON.parse(dataModule.toString());

  const moduleJsonNotContainsShareLibrary1 = dataModuleJson.module?.dependencies.includes('shareLibrary');
  expect(moduleJsonNotContainsShareLibrary1).toBe(false);

  const dataLoadJson = await fs.readFile(
    path.resolve(project.getModule('entry').moduleRootPath(),
      'build/default/intermediates/loader/default/loader.json')
  );

  // 解析JSON5文件
  let loaderJsonContainsShareLibrary1 = false;
  const dataLoadJsonObj = JSON.parse(dataLoadJson.toString());
  for (const dataLoadJsonObjElement in dataLoadJsonObj.hspNameOhmMap) {
    if ('shareLibrary' === dataLoadJsonObjElement) {
      loaderJsonContainsShareLibrary1 = true;
    }
  }
  expect(loaderJsonContainsShareLibrary1).toBe(true);
  const commandsApp = initExecuteCommand({
    mode: 'project',
    product: 'default',
    tasks: 'assembleApp',
  });
  const resultApp = await runHvigorAsync(projectRoot, commandsApp);
  record.addStep('执行App编译构建', resultApp);
  expect(resultApp.stdout).toContain('BUILD SUCCESSFUL');
};

TestCaseBuilder.builder()
  .caseName('OPENLAB_AIDE_ZOS_Build_dynamicDependencies_Import_HSP_01_988')
  .description('ETS服务工程-entry使用dynamicDependencies依赖hsp共享模块')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(taskConfig)
  .testFun(testFun)
  .load();
